#include <stdio.h>
#include "../include/myhead.h"
#include "../include/msg.h"
#include "../include/list_queue.h"
#include "../include/server.h"
#include "../include/ser_pthread.h"
#include "../include/mysqlite.h"

#include <time.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char const *argv[])
{
    int ret;
    int sockfd;

    if(3 == argc)
    {
        set_server_ip(argv[1]);
        set_server_port(atoi(argv[2]));
    }
    else
    {
        printf("No input. Use the default IP address.\n");
        set_server_ip(SERVERIP);
        set_server_port(atoi(SERVERPORT));
        printf("ip:%s:%s\n", SERVERIP, SERVERPORT);
    }

    printf("开启初始化服务器\n");

    // 创建服务器
    if ((sockfd = server_init()) < 0)
    {
        return -1;
    }

    // 初始化数据库
    if (mysqlite_init() == -1)
    {
        return -1;
    }

    // 添加默认数据
    mysqlite_add("admin", "123456", "123123");

    // 初始化链表
    list_t *pclisthead = get_pcclient_list_head();
    list_init(pclisthead);
    list_t *devlisthead = get_device_list_head();
    list_init(devlisthead);

    //初始化消息队列
    msg_queue_init(get_qtod_queue(), 'Q');  //Qt发送到DEV
    msg_queue_init(get_dtoq_queue(), 'D');  //DEV返回到Qt

    printf("msqueue get_qtod_queue :%d\n", *get_qtod_queue());
    printf("msqueue get_dtoq_queue :%d\n", *get_dtoq_queue());

    printf("服务器初始化完成 开启服务\n");

    struct sockaddr_in clientaddr;
    pthread_t pthclient;
    int acceptfd;
    list_t *listnode = NULL;
    while (1)
    {
        memset(&clientaddr, 0, sizeof(clientaddr));
        acceptfd = server_accept(&clientaddr);
        listnode = (list_t *)malloc(sizeof(list_t)); // 申请节点空间，后续用于添加链表
        memset(listnode, 0, sizeof(list_t));
        listnode->client_sockfd = acceptfd;
        listnode->clientaddr = clientaddr;

        // 创建交互线程
        ret = pthread_create(&pthclient, NULL, client_routine, listnode);
        if (ret)
        {
            ERR_LOG("pthread_create error");
        }
        listnode = NULL;
    }

    // 关闭服务器套接字
    close(sockfd);
    return 0;
}
